package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void saveOrUpdate(Employee employee, Long[] ids) {
        if (employee.getId() == null) {
            mapper.insert(employee);
        } else {
            mapper.deleteRelation(employee.getId());
            mapper.updateByPrimaryKey(employee);
        }
        if (ids != null) {
            for (Long rid : ids) {
                mapper.saveRelation(employee.getId(), rid);
            }
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        int rows = mapper.getCount(qo);
        if (rows == 0) {
            return new PageResult(qo.getPageSize());
        }
        List<Employee> list = mapper.selectAll(qo);
        return new PageResult(qo.getCurrentPage(), qo.getPageSize(), rows, list);
    }

    @Override
    public void login(String username, String password) {
        Employee employee = mapper.selectByInfo(username, password);
        if (employee == null) {
            throw new RuntimeException("账号和密码不匹配");
        }
        //登陆成功,把用户信息存入Session中
        UserContext.setCurrentUser(employee);
        //如果用户不是超管,查出用户拥有的权限
        if (!employee.isAdmin()) {
            List<String> exps = permissionMapper.selectExpsByEmployeeId(employee.getId());

            UserContext.setExpressions(exps);
        }

    }


}
